# coding:utf-8
'''
@version: python3.8
@author: ‘eric‘
@license: Apache Licence
@contact: steinven@qq.com
@software: PyCharm
@file: common.py
@time: 2023/10/15 3:26
'''
import configparser
import datetime
import os
import sys
from urllib.parse import urlencode


# 支付宝
from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
from alipay.aop.api.domain.AlipayOpenAppMiniTemplatemessageSendModel import AlipayOpenAppMiniTemplatemessageSendModel
from alipay.aop.api.request.AlipayOpenAppMiniTemplatemessageSendRequest import AlipayOpenAppMiniTemplatemessageSendRequest
app_id = '2021004126608052'
alipay_client_config = AlipayClientConfig(sandbox_debug=False)
alipay_client_config.app_id = app_id  # 应用appID
alipay_client_config.app_private_key = r'MIIEowIBAAKCAQEAqMBP5g4UJEY0umaka2DaDL6cCvkVZC0LcLaniMyueTVPZYcnEV5EtWVcvq3HVQkHmMStEWXLJ95/bs9j2pLRF/+5exeaPxBp2pFo/cJ3Rsl95HXQ/EsfJav/zxKQvvAZ9yXAfu/vdhnt/dqW5ONslnQnhqrfLMmJ+QR0o+y42InChvuHV42DEzDesiTZ5RUt7tmTxx9CJ8qLUMmXZ7hHIQvMreyWnr6D6+aJdzHFyHO20xXzykkKMgPX1pH4TWssN2Cf+J69i3TJvscjNPY2EgGyq9w/476Owgib4P3ZM0GWofXdIQBU4docqjMx9G3Zjxx2RCxuE2vxgROa1swsTwIDAQABAoIBAGxXa/SrvUq8uEWkeJNoDxZ3mf+Bg7ZZJSssWct+fdXb4Cmy5+ZCu6Iqfaz+LSfvMC1ouCSfUhs6wl4GUHmYIR5jVFYvBRzQEOX+zYV+QM31txnielZAdLLfBtGPfdbYmBMQ7dGRghA0/ZMpsA8r5B+EW4weUEKU8jwqHCjSZqq+XH55bteQq928YXFkmzIylkZEFa5hfCe/S/mcdzRgIkr7uLYg/uQwGeFeNSlPzWiDuJVogGEcMHuTb2lLWxcfQIrUONFG8moQXxNMElu2xGpkvujrkRvhLIxuAll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PTBXWrNLvcnCpF+R9xuwduIWfSXdoD2ib+hSEgf8am9ZHdXnKiEa1TUj0/F/GzSUdlvWiU2N4HZ0f5CAB5qZARgcpg3+tXuFyj+p7M31VUlmwhtMEqUKLxW3oA0ZauJwQ2RrMfYRcRPSIVlkjxGrhbpX7lfcKnv/E4DtMNZgQ4Q7gRlEdnsgBOfyJmeE7ua5CymXtiP9kHshpCFJ9YGBgqmvukbaWl7eLiSVB1L3aW7qN1fbYmkmU9ytwTuGcJ/Bt5Og8PHVi614QIDAQAB'  # 公钥


import requests
from loguru import logger
from urllib.parse import quote
from utils.dbtools import update_by_id

if getattr(sys, 'frozen', False):
    BASE_DIR = os.path.dirname(sys.executable)
elif __file__:
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# 创建 ConfigParser 实例
config = configparser.ConfigParser()
logger.info(BASE_DIR)
config.read(os.path.join(BASE_DIR, 'config.ini'),encoding='utf-8')  # 替换为您的配置文件路径

app_id = config.get('wechat', 'app_id')
app_secret = config.get('wechat', 'app_secret')
template_id = config.get('wechat', 'template_id')
grant_type = config.get('wechat', 'grant_type')
miniprogram_state = config.get('wechat', 'miniprogram_state')
appid_map = {
    'wxabbcd9a006426893':'2bab3a8dd73f8d6ee0a93735dddbb33c',
    'wxea519e09916fa7d4':'4470ba476626bab16a5a58456637b157',
    'wxfb5f670247349058':'cc354c1ac33588ea689315f6e3b89074',
    'wx3992aeb767ad62a3':'e3bc68170bdc28de0dc4c23c8bd6efa3',
    'wx9aca4099daeda12f':'fe17a0c56247cd1108d50ad018938a61',
}

registry_path = config.get('app', 'registry_path')
registry_value_name = config.get('app', 'registry_value_name')

url_preffix = config.get('qiniu', 'url_preffix')

base_url = 'https://api.weixin.qq.com/cgi-bin/'


def get_ac(app_id,app_secret):
    u = base_url + 'token'
    p = {
        'grant_type': grant_type,
        'appid': app_id,
        'secret': app_secret,
    }
    r = requests.get(u, params=p)
    return r.json()['access_token']


def send_wx_template(fileName,pan123_file_name):
    '''
    access_token=73_cd2vD1Z5_0x2pRpHG3eieVYQiE9JFCByjUQVs2goeyb4S9ClS91_bwogfInT8UEAwrYEWLic6BMHKpaqnESBdAKV6N-T0OeuhRzF36zlpkuT_iK0tqnA2ns58PgQSDjADAGIT
    :return:
    '''
    global template_id, miniprogram_state
    before_pic_info = get_7niu_pic_info(fileName)
    after_pic_info = get_7niu_pic_info(fileName,True)
    '''{'size': 1871021, 'format': 'png', 'width': 1242, 'height': 2688, 'colorModel': 'nrgba64'}'''
    touser = fileName.split('--')[0]


    before_pic_size = human_size(before_pic_info['size'])
    before_pic_width = before_pic_info['width']
    before_pic_height = before_pic_info['height']

    after_pic_size = human_size(after_pic_info['size'])
    after_pic_width = after_pic_info['width']
    after_pic_height = after_pic_info['height']

    before_link = f'{url_preffix}{fileName}'
    after_link = f'{url_preffix}after/{fileName}'

    if len(fileName.split('--')) > 4:
        scale = fileName.split('--')[-1].split('.')[0]
    else:
        scale = 4


    url_p_dict = {
        'before_link':before_link.replace('all2.jpg','silm.jpg'),
        'after_link':f'https://vip.123pan.cn/1813016409/realpic/{pan123_file_name}',
        'scale':scale,
        'before_pic_size':before_pic_size,
        'before_pic_width':before_pic_width,
        'before_pic_height':before_pic_height,
        'after_pic_size':after_pic_size,
        'after_pic_width':after_pic_width,
        'after_pic_height':after_pic_height,
        'task_result':'success',
        'task_msg':'操作成功',
    }
    if pan123_file_name == None:
        # 123上传失败情况
        url_p_dict.update({
            'after_link':after_link
        })
    if after_pic_info['size'] >100*1024*1024:
        url_p_dict.update({
            'task_result':'fail',
            'task_msg':'处理后的图片大于100MB，禁止直接保存！请复制链接后，通过其它方式下载',
        })
    elif after_pic_info['size'] >150*1024*1024:
        url_p_dict.update({
            'task_result': 'fail',
            'task_msg': '处理后的图片大于150MB，禁止下载！请联系客服处理',
        })

    logger.info(url_p_dict)
    url_params = urlencode(url_p_dict)


    # out_file_size = human_size(after_pic_size)
    # 获取当前时间
    current_time = datetime.datetime.now().replace(microsecond=0)

    # 格式化日期字符串
    current_time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')

    # 添加 30 天
    expiration_date = current_time + datetime.timedelta(days=3)

    # 支付宝
    if touser.startswith('2088'):
        client = DefaultAlipayClient(alipay_client_config)
        model = AlipayOpenAppMiniTemplatemessageSendModel()
        model.data = {
            "keyword1": {
                "value": '已完成'
            },
            "keyword2": {
                "value": "图片放大"
            },
            "keyword3": {
                "value": "点击查看结果"
            },
            "keyword4": {
                "value": f'{current_time}'
            },
            "keyword5": {
                "value": f'{expiration_date}'
            }
        }
        url_params = quote(urlencode(url_p_dict), safe='')
        logger.info(f"/pages/result/result?{url_params}")
        model.page = f"/pages/result/result?{url_params}"
        model.user_template_id = 'ae0029bc860a4255b89bbdc5fc95ccd1'
        model.to_user_id = touser
        request = AlipayOpenAppMiniTemplatemessageSendRequest(model)
        r = client.execute(request)
        logger.info(r)
    else:
        fileNameList = fileName.split('--')
        u = base_url + 'message/subscribe/send'

        p = {
            'access_token': get_ac('wx9aca4099daeda12f','fe17a0c56247cd1108d50ad018938a61'),
        }
        if len(fileNameList)>4:
            app_id = fileNameList[0]
            app_secret = appid_map[app_id]
            p = {
                'access_token': get_ac(app_id,app_secret),
            }
            template_id = fileNameList[1]
            touser = fileName.split('--')[2]
            # miniprogram_state = 'trial'
        else:
            template_id = config.get('wechat', 'template_id')
            touser = fileName.split('--')[1]
            # miniprogram_state = 'formal'
        post_json = {
            "touser": touser,
            "template_id": f"{template_id}",
            "page": f"/pages/result/result?{url_params}",
            "miniprogram_state": f"{miniprogram_state}",
            "lang": "zh_CN",
            "data": {
                "thing1": {
                    "value": f"【{scale}X】 | 【{after_pic_size}】"
                },
                "thing3": {
                    "value": "点击查看结果"
                },
                "date2": {
                    "value": f'{current_time}'
                },
                "date4": {
                    "value": f'{expiration_date}'
                },
                "phrase9": {
                    "value": "已完成"
                }
            }
        }
        logger.info(f'params:{p}')
        logger.info(f'post_json:{post_json}')
        r = requests.post(u, params=p,json=post_json)
        logger.debug(r.text)
        if r.status_code==200:
            update_by_id(fileName,
                         {
                             'status_code': 4,
                             'status_desc': '消息发送成功',
                             'before_link': before_link,
                             'after_link': after_link,
                             'scale': int(scale),
                             'before_pic_size': int(before_pic_info['size']),
                             'after_pic_size': int(after_pic_info['size']),
                             'before_pic_width': int(before_pic_width),
                             'after_pic_width': int(after_pic_width),
                             'before_pic_height': int(before_pic_height),
                             'after_pic_height': int(after_pic_height),
                         }
                         )
        else:
            update_by_id(fileName, {'status_code': 5, 'status_desc': '消息发送失败'})


def get_7niu_pic_info(fileName,isAfter=False):
    logger.info(fileName)
    if isAfter:
        r = requests.get(f'{url_preffix}after/{fileName}?imageInfo')
        return r.json()
    else:
        fileName = fileName.replace('-all2.jpg','')
        r = requests.get(f'{url_preffix}{fileName}?imageInfo')
        return r.json()


def human_size(bytes_size):
    if bytes_size >= 1024 * 1024:
        return f"{round(bytes_size / (1024 * 1024), 1)}MB"
    else:
        return f"{round(bytes_size / 1024, 1)}KB"


def get_file_size(file_path):
    bytes_size = os.path.getsize(file_path)

    return human_size(bytes_size)


def get_file_raw_size(file_path):
    bytes_size = os.path.getsize(file_path)

    return bytes_size


def exec_cmd(command):
    import subprocess
    # 使用 subprocess 执行命令并等待其完成
    completed_process = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

    # 获取命令的标准输出和标准错误输出
    stdout_output = completed_process.stdout
    stderr_output = completed_process.stderr

    # 获取命令的返回码
    return_code = completed_process.returncode
    logger.debug("标准输出:", stdout_output)
    logger.debug("标准错误输出:", stderr_output)
    logger.debug(f'return_code:{return_code}')
    return return_code

def set_scale(scale_size):
    import winreg
    new_value = str(scale_size)  # 替换为要设置的新值
    try:
        # 打开注册表
        with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as root_key:
            # 打开注册表键
            with winreg.OpenKey(root_key, registry_path, 0, winreg.KEY_WRITE) as key:
                # 设置新的键值
                winreg.SetValueEx(key, registry_value_name, 0, winreg.REG_SZ, new_value)

        logger.info(f"成功将键值 '{registry_value_name}' 修改为 '{new_value}'")
    except Exception as e:
        logger.info("修改注册表键值时出错:", e)


def send_warn_msg(opnid):
    template_id= '7orKvP5GojgrvamGJyaX0dCKHnQml2B8MFuK_zqjgj0'
    # 获取当前时间
    current_time = datetime.datetime.now().replace(microsecond=0)
    u = base_url + 'message/subscribe/send'

    # 添加 30 天
    expiration_date = current_time + datetime.timedelta(days=30)
    p = {
        'access_token': get_ac(app_id, app_secret),
    }
    post_json = {
        "touser": opnid,
        "template_id": f"{template_id}",
        "page": f"/pages/index/index",
        "miniprogram_state": f"{miniprogram_state}",
        "lang": "zh_CN",
        "data": {
            "thing1": {
                "value": f"↓↓↓↓图片违规↓↓↓↓↓"
            },
            "thing3": {
                "value": "若再上传违规内容，永久封禁！"
            },
            "date2": {
                "value": f'{current_time}'
            },
            "date4": {
                "value": f'{expiration_date}'
            },
            "phrase9": {
                "value": "失败"
            }
        }
    }
    logger.info(f'post_json:{post_json}')
    r = requests.post(u, params=p, json=post_json)
    logger.debug(r.text)
    if r.status_code == 200:
        logger.info('发送警告消息成功~')
    else:
        logger.info('发送警告消息失败！！')

def check_img(b_link):
    '''
    鉴黄，传入七牛的链接，拼接成silm缩略后再进行检测
    Parameters
    ----------
    b_link

    Returns True<=====>无害
    -------

    '''
    try:
        logger.info(f'图片检测：{b_link}')
        p = {
            'url': b_link.replace('all2.jpg', 'silm.jpg')
        }
        r = requests.get('http://192.168.123.222:8080', params=p, timeout=10)
        for i in r.json():
            if i['className'] == 'Hentai' or i['className'] == 'Porn':
                probability = i['probability']
                if probability > 0.6:
                    logger.info(f'不良率：{probability}')
                    return False
            else:
                return True
    except:
        return False
if __name__ == '__main__':
    # get_7niu_pic_info('http://realpic.00123.fun/o8_mB4oseDyakqp6qr_XRZOwfIew--307b0d501289e5d0c203e3d26f968d19--4.png')
    send_warn_msg('oo2Yw5cEHBbLgwvu8ilrWDbKIIuw')